<?php

/**
 * 勤记录详情bll,如果27号30\31假，在28号结算的时候,数据还没有写入
*/
apf_require_class("Bll_BLL");
apf_require_class("Tools_OAUrls");
apf_require_class('Bll_Attendance_MonthSpecialSet');
apf_require_class('Bll_Attendance_DailyReport');
apf_require_class('Tools_Tools');
apf_require_class('Bll_Attendance_UserInfo');
apf_require_class('Bll_Attendance_UserExt');
apf_require_class('Bll_Attendance_AccessDayRecord');
class Bll_Attendance_DailyLeave extends BLL{
    /******* opt user_day_status *******/
    public function find_kq_by_dateline($uid,$dateline){
        $data = $this->get_kq_dao()->find(array('user_id'=>$uid,'dateline'=>$dateline));
        if(!empty($data)){
            return $data[0];
        }
        return $data;
    }
    private $uid;
    //判断是不是本人查看
    private function is_self(){
        if($this->uid == $_SESSION['user_id']){
            return true;
        }
        return false;
    }
    /**
     * 每日状态，考勤明细计算
     * @param int $uid
     * @param int $start Ymd
     * @param int $end   Ymd
     *
     * //测试需要
     * set_user_info     用户信息
     * set_attendance    每日打卡状态
     * set_record        每日打卡记录
     * set_check_day_work_status check打卡状态
     * set_prev_data     上月未清数据记录
     * set_curr_data     迟到公出出差早退数据记录
     * set_next_data     用户请假记录每半天区分
     * set_leaves_on_ids 用户请假记录
     */
    public function get_attendance_list($uid,$start,$end){
        $this->uid = $uid;

        $userinfo = $this->get_user_info($uid);

        $end_date = intval(str_replace('-','',substr($userinfo['enter_date'],0,10)));//入职时间
        $dimission_date = intval(str_replace('-','',substr($userinfo['dimission_date'],0,10)));//入职时间

        $year = substr($start,0,4);
        $month = substr($start,4,2);

        $result = array();
        //查询每日状态
        $day_list = $this->get_attendance($uid,$start,$end);
        if(empty($day_list)){
            return $result;
        }
        $kq_exception = array();
        foreach($day_list as $val){
            if($val['am_status']!=5 || $val['pm_status']!=6){//今天考勤异常，需要去找请假记录
                $kq_exception[] = $val['dateline'];
            }
            $each = strtotime($val['dateline']);
            $val['month'] = date('m',$each);
            $val['day'] = date('d',$each);
            $val['week'] = Tools_Tools::get_instance()->convert_chinese_week(date('w',$each));
            $val['kq_detail']=array();
            $val['work_time_txt']='';
            $result[$val['dateline']] = $val;
        }
        //查找打卡记录
        $access_list = $this->get_record($uid,$start,$end);

        if(!empty($access_list)){//有可能最近一周都没有打卡记录
            foreach($access_list as $val){
                if(isset($result[$val['access_date']])){
                    $status=$this->get_check_day_work_status($val['access_date'],$val['start_work'], $val['end_work']);
                    if($status[0]==5 && $status[1]==6){
                        $result[$val['access_date']]['work_time_txt']='正常';
                    }else{
                        $result[$val['access_date']]['work_time_txt']=$val['start_work'].'-'.$val['end_work'];
                    }
                    $result[$val['access_date']]['kq_detail']=$val;
                }
            }
        }
        //所有请假记录的id
        $leave_ids = array();
        $where=array(
                'user_id'=>$uid,
                "dateline >=$start AND dateline <=$end AND 1=?"=>1
        );
        //得到表user_last_leave_record
        $prev_data = $this->get_prev_data($where);
        if(!empty($prev_data)){
            foreach($prev_data as $val){
                if($val['leave_status']==1 || $val['leave_status']==2){
                    $apm_key = 'apm';
                    if($val['leave_apm']==1){
                        $apm_key = 'am';
                    }elseif($val['leave_apm']==2){
                        $apm_key = 'pm';
                    }
                    $result[$val['dateline']][$apm_key][]=array(
                                'leave_id'=>$val['leave_id'],
                                'leave_type'=>$val['leave_type'],
                                'leave_status'=>$val['leave_status'],
                                'debug_info'=>'prev'
                                );
                    $leave_ids[] = $val['leave_id'];
                }
            }
        }
        //得到user_leave_daily"
        $curr_data = $this->get_curr_data($where);
        if(!empty($curr_data)){
            foreach($curr_data as $val){
                if($val['leave_status']==1 || $val['leave_status']==2){
                    $apm_key = 'apm';
                    if($val['leave_apm']==1){
                        $apm_key = 'am';
                    }elseif($val['leave_apm']==2){
                        $apm_key = 'pm';
                    }
                    $result[$val['dateline']][$apm_key][]=array(
                            'leave_id'=>$val['leave_id'],
                            'leave_type'=>$val['leave_type'],
                            'leave_status'=>$val['leave_status'],
                            'debug_info'=>'curr'
                    );
                    $leave_ids[] = $val['leave_id'];
                }
            }
        }
        //print_r($curr_data);exit;
        //得到user_leave_record_ext
        $next_data = $this->get_next_data($where);
        if(!empty($next_data)){
            foreach($next_data as $val){
                if($val['am_leave_status']==1||$val['am_leave_status']==2|| $val['pm_leave_status']==1 || $val['pm_leave_status']==2){
                    if($val['am_leave_id'] && $val['am_leave_id']==$val['pm_leave_id']){//全天的
                        $result[$val['dateline']]['apm'][]=array(
                                'leave_id'=>$val['am_leave_id'],
                                'leave_type'=>$val['am_type'],
                                'leave_status'=>$val['am_leave_status'],
                                'debug_info'=>'next'
                        );
                        $leave_ids[] = $val['am_leave_id'];
                    }else{
                        if(!empty($val['am_leave_id'])){
                            $result[$val['dateline']]['am'][]=array(
                                    'leave_id'=>$val['am_leave_id'],
                                    'leave_type'=>$val['am_type'],
                                    'leave_status'=>$val['am_leave_status'],
                                    'debug_info'=>'next'
                            );
                            $leave_ids[] = $val['am_leave_id'];
                        }
                        if(!empty($val['pm_leave_id'])){
                            $leave_ids[] = $val['am_leave_id'];
                            $result[$val['dateline']]['pm'][]=array(
                                    'leave_id'=>$val['pm_leave_id'],
                                    'leave_type'=>$val['pm_type'],
                                    'leave_status'=>$val['pm_leave_status'],
                                    'debug_info'=>'next'
                            );
                            $leave_ids[] = $val['pm_leave_id'];
                        }
                    }
                }
            }
        }
        //再格式化一下
        $result = $this->format_attendance_list($result);
        $leave_ids = array_unique($leave_ids);
        $where_record = array(
                "id IN(".implode(',',$leave_ids).") AND 1=?"=>1
        );
        $leave_record = $this->get_leaves_on_ids($leave_ids);
        $leave_data = array();
        foreach($leave_record as $val){//只返回需要的字段
            $leave_data[$val['id']] = $val;
        }
        //显示数据处理
        //print_r($leave_data);exit;
        //print_r($result);exit;
        $result = $this->_do_to_view($result,$leave_data,$end_date,$dimission_date,$userinfo);
        return $result;
    }
    //主要是对周6日 节假日等处理
    private function format_attendance_list($result){
        $holiday = Tools_Tools::get_instance()->each_year_holiday_country();
        $kq_status = APF::get_instance()->get_config('kq_status');
        $tmp =array();
        foreach ($result as $day =>$val){
            $each = strtotime($day);
            if(date('w',$each) != 6 && date('w',$each) != 0) {
                if(in_array(date('Y-m-d',$each),$holiday)) {
                    $tmp['status'][0] = array('id' => 999,'name' => '法定节假日');
                }else{
                    $stats = $val['am_status'].'0'.$val['pm_status'];
                    if($stats !=506){//说明状态不正常
                        $val['status_txt']=$kq_status[$stats];
                    }
                }
            }
            $result[$day]=$val;
        }
        return $result;
    }

    private $_userinfo;
    private $bll_user;
    /**
     * $test_userinfo 为测试专用
     */
    public function set_user_info($test_userinfo = ''){
        $this->_userinfo = $test_userinfo;
    }
    /**
     * 获取用户信息
     */
    public function get_user_info($uid){
        if($this->_userinfo && $this->_userinfo['user_id']==$uid){
        }else{
            if(!$this->bll_user){
                $this->bll_user = new Bll_Attendance_UserInfo();
            }
            $users = $this->bll_user->get_user_by_ids($uid);
            $userinfo = $users[0];
            $this->_userinfo = $userinfo;
        }
        return $this->_userinfo;
    }
    private $_day_attendance;
    private $_key_attendance;
    /**
     * $test_result 为测试专用
     */
    public function set_attendance($uid,$start,$end,$test_result = ''){
       $this->_day_attendance = $test_result;
       $this->_key_attendance = ''.$uid.$start.$end;
    }
    /**
     *  查询每日状态
     */
    public function get_attendance($uid,$start,$end){
        $key = ''.$uid.$start.$end;
        if($this->_day_attendance && $this->_key_attendance == $key){
        }else{
            $this->_key_attendance = $key;
            $where=array(
                    'user_id'=>$uid,
                    "dateline >=$start AND dateline <=$end AND 1=?"=>1
            );
            $this->_day_attendance = $this->get_kq_dao()->find($where);
        }
        return $this->_day_attendance;
    }
    private $_key_record;
    private $_day_record;
    /**
     * 查找打卡记录
     */
    public function set_record($uid,$start,$end,$test_result){
        $this->_day_record = $test_result;
        $this->_key_record = ''.$uid.$start.$end;
    }
    /**
     * 查找打卡记录
     */
    public function get_record($uid,$start,$end){
        $key = ''.$uid.$start.$end;
        if($this->_day_record && $this->_key_record == $key){

        }else{
            $this->_key_record = $key;
            $access_where = array(
                'user_id'=>$uid,
                "access_date >=$start AND access_date <=$end AND 1=?"=>1
            );
            $acc_dao = $this->get_dao('Dao_Attendance_AccessDayRecord');
            $this->_day_record = $acc_dao->find($access_where);
        }
        return $this->_day_record;
    }

    private $_status;
    private $acc_bll;
    public function set_check_day_work_status($test_status){
        $this->_status = $test_status;
    }
    /**
     * 检查打卡状态
     */
    public function get_check_day_work_status($access_date,$start_work,$end_work){
        $key = ''.$access_date.$start_work.$end_work;
        if($this->_status && isset($this->_status[$key])){

        }else{
            if(!$this->acc_bll){
                apf_require_class('Bll_Attendance_AccessDayRecord');
                $this->acc_bll = new Bll_Attendance_AccessDayRecord();
            }
            $this->_status[$key]=$this->acc_bll->check_day_work_status($access_date,$start_work,$end_work);
        }
        return $this->_status[$key];
    }
    private $_leaves;
    private $_leave_bll;
    /**
     * 所有请假记录
     *  $leaves=array(
     *      [20005] => Array
                (
                    [id] => 20005
                    [user_id] => 7119
                    [apply_time_ext] => 1350023581
                    [start_time] => 2012-10-12 09:00
                    [end_time] => 2012-10-12 18:00
                    [leave_time] => 9.0
                    [type] => 公出
                    [leave_reason] => 公出
                    [leave_desc] => 爱房自营销启动，在外面开会
                    [status] => 已批准
                    [img] =>
                )
        )
     */
    public function set_leaves_on_ids($leaves){
        $this->_leaves = $leaves;
    }
    public function get_leaves_on_ids($ids){
        $key = join('_', $ids);
        if($this->_leaves && isset($this->_leaves[$key])){

        }else{
            if(!$this->_leave_bll){
                apf_require_class('Bll_Attendance_LeaveRecord');
                $this->_leave_bll = new Bll_Attendance_LeaveRecord();
            }
            $this->_leaves[$key]=$this->_leave_bll->get_leave_by_ids($ids);
        }
        return $this->_leaves[$key];
    }
    //每个月的结算日
    private function _get_month_special_set($start,$end){
        $result = array();
        $month_bll = new Bll_Attendance_MonthSpecialSet();
        $one_day = 24*60*60;
        for($i = strtotime($start);$i<=strtotime($end);$i+=$one_day){
            $yearmonth = date('Ym',$i);
            if(!isset($result[$yearmonth])){
                $month_set = $month_bll->get_month_special_set($yearmonth);
                $result[$yearmonth] = $month_set['settlement'];
            }
        }
        return $result;
    }
    public function get_report_data_new($uid,$start,$end){
        $result = array();
        //获取结算日
        $month_set = $this->_get_month_special_set($start, $end);
        //获取记录
        $where=array(
                'user_id'=>$uid,
                "dateline >=$start AND dateline <=$end AND 1=?"=>1
        );
        $day_list = $this->get_kq_dao()->find($where);
        $temp_leave = array();
        foreach($day_list as $one){
            $temp_leave[$one['dateline']] = $one;
        }
        unset($day_list);
        $one_day = 24*60*60;
        for($i = strtotime($start);$i<=strtotime($end);$i+=$one_day){
             $now_ymd = date('Ymd',$i);
             $now_ym  = date('Ym',$i);
             $start_ymd = date('Ym',mktime(0,0,0,date('m',$i),1,date('Y',$i)));
             $end_ymd = date('Ym',mktime(0,0,0,date('m',$i)+1,-1,date('Y',$i)));
             if($now_ymd >= $start_ymd && $now_ymd <= $month_set[$now_ym]){
                 $result[$now_ym]['now'][$now_ymd] = $temp_leave[$now_ymd];
             }
             if($end_ymd > $month_set[$now_ym]){
                 if($now_ymd > $month_set[$now_ym] && $now_ymd <= $end_ymd){
                     $pre_ym  = date('Ym',mktime(0,0,0,date('m',$i)-1,1,date('Y',$i)));
                 }
             }
        }
    }

    private $before_settlement_data=array();
    private $after_settlement_data=array();
    private $last_settlement_data=array();
    private $curr_settlement='';//前个月的结算日
    private $prev_settlement='';//上一个月的结算日
    //结算日之前 0701-0728
    public function set_before_settlement_data($key,$data=array()){
        $this->before_settlement_data[$key] = $data;
    }
    /**
     * 结算日之前 0701-0728  1101-1130
     * @param int $uid
     * @param int $start
     * @param int $end
     * @return multitype:
     */
    public function get_before_settlement_data($uid,$start,$end){
        $key=$uid.'-'.$start.'-'.$end.'-before';
        if(!empty($this->before_settlement_data[$key])){
            return $this->before_settlement_data[$key];
        }
        $where=array(#查询上个月结算日到这个月结算日的假
                'user_id'=>$uid,
                "dateline >=$start AND dateline <=$end AND 1=?"=>1
        );
        $this->before_settlement_data[$key] = $this->get_kq_dao()->find($where);
        return $this->before_settlement_data[$key];
    }
    //结算日到月底
    public function set_after_settlement_data($key,$data=array()){
        $this->after_settlement_data[$key] = $data;
    }
    /**
     * 结算日到月底 0729-0731
     * 如果是自然月作为结算就没有这一项
     * @param int $uid
     * @param int $start
     * @param int $end
     * @return multitype:
     */
    public function get_after_settlement_data($uid,$start,$end){
        $key=$uid.'-'.$start.'-'.$end.'-after';
        if(!empty($this->after_settlement_data[$key])){
            return $this->after_settlement_data[$key];
        }
        $this->after_settlement_data[$key] = $this->get_ext_record($uid,$start,$end);
        return $this->after_settlement_data[$key];
    }
    //上月未清
    public function set_last_settlement_data($key,$data=array()){
        $this->last_settlement_data[$key] = $data;
    }
    /**
     * 上月未清
     * 28号结算 29,30,31默认为正常,上月未清 0701-0731
     * 月底最后一天结算 上月未清 0701-0731
     * @param int $uid
     * @param int $start
     * @param int $end
     */
    public function get_last_settlement_data($uid,$start,$end){
        $key=$uid.'-'.$start.'-'.$end.'-last';
        if(!empty($this->last_settlement_data[$key])){
            return $this->last_settlement_data[$key];
        }
        $prev_where = array(
                'user_id'=>$uid,
                'leave_status'=>2,
                "dateline >=$start AND dateline <=$end AND 1=?"=>1
        );
        $this->last_settlement_data[$key] = $this->get_prev_dao()->find($prev_where);
        return $this->last_settlement_data[$key];
    }
    private $month_work_days=array();
    public function set_month_work_day($data){
        return $this->month_work_days;
    }
    /**
     * 得到当前月和前一个月的工作日
     * @param int $month 201208
     */
    public function get_month_work_day($year,$month){
        $key = $year.'='.$month;
        if(!empty($this->month_work_days[$key])){
            return $this->month_work_days[$key];
        }

        $curr_time = date('Ym',mktime(0,0,0,$month,1,$year));
        $prev_time = date('Ym',mktime(0,0,0,$month-1,1,$year));

        $prev_work_day_list = Tools_Tools::get_instance()->actual_work_day_by_month_list($prev_time);//上个月需要上班的日子
        $curr_work_day_list = Tools_Tools::get_instance()->actual_work_day_by_month_list($curr_time);//查询月那些日子需要上班
        $this->month_work_days[$key] = array_merge($prev_work_day_list,$curr_work_day_list);
        return $this->month_work_days[$key];
    }
    /**
     * 分三段计算
     * 0801-0828
     * 0728-0801
     * 公出算的是1-30号
     * 上月未清
     * 结算日后入职的
     * @param int $uid
     * @param int $start
     * @param int $end
     * @return number|Ambigous <number, unknown>
     */
    public function get_report_data($uid,$start,$end){
        $this->report_start = $start;
        $this->report_end = $end;
        $userinfo = $this->get_user_info($uid);

        $end_date = intval(str_replace('-','',substr($userinfo['enter_date'],0,10)));//入职时间
        $dimission_date = intval(str_replace('-','',substr($userinfo['dimission_date'],0,10)));//入职时间
        $is_sale_partment=0;//员工是否销售部，不计旷工和迟到
        $sale_department = APF::get_instance()->get_config('sale_department');

        $city_card = APF::get_instance()->get_config('city_card');
        $city_names = array_values($city_card);
        //没有开通打卡的城市和销售部统一作为销售部处理
        if(!in_array($userinfo['city_name'],$city_names) || !empty($sale_department[$userinfo['department_id']])){
            $is_sale_partment=1;
        }
        $year = substr($start,0,4);
        $month = substr($start,4,2);

        $month_bll = new Bll_Attendance_MonthSpecialSet();
        $yearmonth = substr($start,0,6);
        $month_set = $month_bll->get_month_special_set($yearmonth);
        $month_set_day = $month_set['settlement'];#得到这个月的结算日
        $this->curr_settlement = $month_set['settlement'];

        $curr_month_end = mktime(0,0,0,$month,0,$year);
        $prev_start = mktime(0,0,0,$month-1,1,$year);
        //取上个月的结算日
        $prev_yearmonth = date('Ym',$prev_start);
        $month_set_prev = $month_bll->get_month_special_set($prev_yearmonth);
        $prev_date = $month_set_prev['settlement'];#得到上个月的结算日
        $this->prev_settlement = $month_set['settlement'];

        $work_days = Tools_Tools::get_instance()->current_month_work_day($year,$month);
        $result['work_att_day']=$work_days;//应出勤
        $result['rice_day'] = 0;//餐补天数
        $result['oa_kg'] = 0;
        $result['oa_cd'] = 0;
        $result['oa_gc'] = 0;
        $result['oa_gc_passed'] = 0;
        $result['oa_cc'] = 0;
        $result['oa_cc_passed'] = 0;
        $result['oa_sj'] = 0;
        $result['oa_sj_passed'] = 0;
        $result['oa_bj'] = 0;
        $result['oa_bj_passed'] = 0;
        $result['oa_nj'] = 0;
        $result['oa_nj_passed'] = 0;
        $result['oa_oj'] = 0;
        $result['oa_oj_passed'] = 0;
        $result['other_more'] = array();
        $result['oa_prexj'] = array();
        $result['oa_prexj_info'] = array();
        $result['meal'] = 0;
        $result['work_act_day'] = 0;//实际出勤
        $result['work_act_not_day'] = 0;//未全勤
        $result['oa_url'] = Tools_OAUrls::get_instance()->build_user_detail_url($uid,$year.$month);
        //当天入职，当天离职
        if($end_date==$dimission_date){
            return $result;
        }
        //不计算餐补的天数
        $have_half_day=array();
        //************第一段计算 1号到结算日的 0801-0828
        $day_list = $this->get_before_settlement_data($uid,$start,$month_set_day);
        if(empty($day_list)){
            return $result;
        }
        //************第一段计算 0828-0901 查看是否有结算日之前请的假，应该直接扣除
        $next_one_month = date('Ymd',mktime(0,0,0,$month+1,1,$year));
        $record_ext = $this->get_after_settlement_data($uid,$month_set_day,$next_one_month);
        if(!empty($record_ext)){
            $day_list = array_merge($day_list,$record_ext);
        }
        //取员工的当月打卡记录
        $access_bll = new Bll_Attendance_AccessDayRecord();
        $prev_start_day = date('Ymd',$prev_start);
        $tmp_access_record = $access_bll->get_record_list($uid,$prev_start_day,$next_one_month);
        $access_record = array();
        if(!empty($tmp_access_record)){
            foreach($tmp_access_record as $val){
                $access_record[$val['access_date']] = $val;
            }
        }

        //取出上下两个月需要上班的工作日
        $work_list = $this->get_month_work_day($year,$month);
        //当月入职与当月离职//$this->get_curr_month_n_work($userinfo,$start,$end);
        $curr_not_work = Tools_Tools::get_instance()->current_month_not_work_day($year,$month,date('Ymd',strtotime($userinfo['enter_date'])),date('Ymd',strtotime($userinfo['dimission_date'])));
        //算实际出勤的假
        $is_act_type=array('出差','年假','丧假','婚假','产检','陪产假');
        $is_meal_type=array(#算餐补的,
                Const_LeaveType::LEAVE_TYPE_CHUCHA,
                );
        $is_not_act_type=array(#不计算实际出缺勤的
                Const_LeaveType::LEAVE_TYPE_SHIJIA,
                Const_LeaveType::LEAVE_TYPE_BINGJIA,
                Const_LeaveType::LEAVE_TYPE_CHANQIANJIA,
                Const_LeaveType::LEAVE_TYPE_CHANJIA
                );
        $show_type = array(#报表中显示的项,不算公出,公出在最下面处理 1-30号
                //Const_LeaveType::LEAVE_TYPE_GONGCHU=>'oa_gc',
                Const_LeaveType::LEAVE_TYPE_CHUCHA=>'oa_cc',
                Const_LeaveType::LEAVE_TYPE_SHIJIA=>'oa_sj',
                Const_LeaveType::LEAVE_TYPE_BINGJIA=>'oa_bj',
                Const_LeaveType::LEAVE_TYPE_NIANJIA=>'oa_nj',
        );
        /********Debug********/
        $debug_info=array();
        $leave_type = APF::get_instance()->get_config('leave_type');

        $holiday =  Tools_Tools::get_instance()->each_year_holiday_country();
        foreach($day_list as $val){
            $today = $val['dateline'];
            $stday = date('Y-m-d',strtotime($val['dateline']));
            if(!in_array($stday,$holiday)){//法定节假日请产假，产前假，都不算餐补
                if(!in_array($today,$work_list)){//不是工作日
                    continue;
                }
                if($today <=$end_date){//小于入职时间的不算
                    continue;
                }
                if($dimission_date && $today >$dimission_date){//大于离职时间的不算
                    continue;
                }
                if($today >$end){//如果是请今天之后的假,同时还不到月底
                    continue;
                }

                //状态异常时，缺勤和公出会修正状态,但没有am_type pm_type，不计算
                if($val['am_status']==5 && $val['pm_status']==6 && empty($val['am_type']) && empty($val['pm_type'])){
                    continue;
                }
            }else{//节假日请的不是产假或是产前假，不处理
                if($val['am_type']!=Const_LeaveType::LEAVE_TYPE_CHANQIANJIA && $val['am_type']!=Const_LeaveType::LEAVE_TYPE_CHANJIA){
                    continue;
                }
            }
            if($val['am_type']==Const_LeaveType::LEAVE_TYPE_CHIDAO || $val['pm_type']==Const_LeaveType::LEAVE_TYPE_ZAOTUI ){
                continue;
            }
            //特殊班别，不是全天缺勤的，都算正常
            if ($userinfo['user_type'] == 1 && $today >= $userinfo['user_type_date']) {
                if(in_array($today,$work_list)){//不是工作日
                    if($val['am_status']==3 && $val['pm_status']==4){
                        if(empty($access_record[$today]['start_work'])){
                            $result['oa_kg'] +=1;
                            $have_half_day[$today]=1;
                            $debug_info['oa_kg'][]=$today;
                        }
                    }
                }
            }else{
                if(!$is_sale_partment){//销售部，不计旷工和迟到
                    if(in_array($today,$work_list)){//产假和产前假，fei工作日也统计天数，但旷工不算
                        if($val['am_status']==3){
                            $result['oa_kg'] +=0.5;
                            $debug_info['oa_kg'][]=$today;
                        }
                        if($val['pm_status']==4 && $today!=date('Ymd')){//如果是查询当天的，不计下午
                            $result['oa_kg'] +=0.5;
                            $debug_info['oa_kg'][]=$today;
                        }
                        if(($val['am_status']==3 || $val['pm_status']==4)){//上下午有缺勤,出去掉餐补
                            $have_half_day[$today]=1;
                        }
                        if($val['is_later']){
                            $result['oa_cd'] +=1;
                            $debug_info['cd'][] =$today;
                        }
                    }
                }
            }

            //公出\缺勤算餐补,其他请假不算
            if($val['am_type']){
                $am_key = isset($show_type[$val['am_type']]) ? $show_type[$val['am_type']] : 'oa_oj';
                if($val['am_leave_status']==1 || $val['am_leave_status']==2){
                    $result[$am_key] +=0.5;
                    if($am_key=='oa_oj'){
                        $result['tmp_other_more'][$val['am_type']]['all'] += 0.5;
                        $debug_info['tmp_other_more'][$val['am_type']][]=$today.'-'.$leave_type[$val['am_type']].'-'.$val['am_leave_status'];
                    }
                    $debug_info[$leave_type[$val['am_type']]][$today]=$val['am_leave_status'];
                }
                if($val['am_leave_status']==2){#这里防止有撤消的假影响
                    $result[$am_key.'_passed'] +=0.5;
                    if($am_key=='oa_oj'){
                        $result['tmp_other_more'][$val['am_type']]['passed'] += 0.5;
                    }
                    //请假通过时去掉餐补
                    if($val['am_type']!=Const_LeaveType::LEAVE_TYPE_CHUCHA){
                        $have_half_day[$today]=1;
                    }
                }
            }
            if($val['pm_type']){
                $pm_key = isset($show_type[$val['pm_type']]) ? $show_type[$val['pm_type']] : 'oa_oj';
                if($val['pm_leave_status']==1 || $val['pm_leave_status']==2){
                    $result[$pm_key] +=0.5;
                    if($pm_key=='oa_oj'){
                        $result['tmp_other_more'][$val['pm_type']]['all'] += 0.5;
                    }
                    $debug_info[$leave_type[$val['pm_type']]][$today]=$val['pm_leave_status'];
                }
                if($val['pm_leave_status']==2){#这里防止有撤消的假影响
                    $result[$pm_key.'_passed'] +=0.5;
                    if($pm_key=='oa_oj'){
                        $result['tmp_other_more'][$val['pm_type']]['passed'] += 0.5;
                    }
                    //请假通过时去掉餐补
                    if($val['pm_type']!=Const_LeaveType::LEAVE_TYPE_CHUCHA){
                        $have_half_day[$today]=1;
                    }
                }
            }

            if(($val['am_status']==3 || $val['pm_status']==4) && !$is_sale_partment){//上下午有缺勤,出去掉餐补
                if ($userinfo['user_type'] ==1 && $today >= $userinfo['user_type_date']) {
                    if($val['am_status']==3 && $val['pm_status']==4){
                        if(empty($access_record[$today]['start_work'])){
                            $have_half_day[$today]=1;
                        }
                    }else{

                    }
                }else{
                    $have_half_day[$today]=1;
                }
            }

            //出差,年假,产检算实际出缺勤
            if($val['am_leave_status']==2 && in_array($val['am_type'],$is_not_act_type)){
                $result['not_act_work'] += 0.5;
                $debug_info['not_act_work'][]=$today.'-'.$leave_type[$val['am_type']].'-'.$val['am_leave_status'];
            }
            if($val['pm_leave_status']==2 && in_array($val['pm_type'],$is_not_act_type)){
                $result['not_act_work'] += 0.5;
                $debug_info['not_act_work'][]=$today.'-'.$leave_type[$val['pm_type']].'-'.$val['pm_leave_status'];
            }
        }//endforeach
        //如果没有入职
        if($is_sale_partment){
            $result['oa_cd'] =0;
            $result['oa_kg'] =0;
            //$have_half_day=array();
        }
        $result['rice_day'] = $work_days - count($have_half_day)- $curr_not_work;
        $result['meal'] = $this->get_meal($work_days, $result['rice_day']);
        $result['work_act_day'] =$work_days - $result['oa_kg'] - $result['not_act_work'] - $curr_not_work;

        //入职当月，且是28号之后入职的,大于结算日后入职的
        if( $end_date <= $end && $end_date > $month_set_day){
            $result['work_act_day'] = 0;
            $result['rice_day'] = 0;
            $result['meal'] = 0;
            $result['work_act_not_day'] =  $work_days;
        }else{
            $result['work_act_not_day'] = $curr_not_work;//Tools_Tools::get_instance()->current_month_not_work_day($year,$month,date('Ymd',strtotime($userinfo['enter_date'])),date('Ymd',strtotime($userinfo['dimission_date'])));
        }
        if(!empty($result['tmp_other_more'])){//格式化其它
            foreach ($result['tmp_other_more'] as $l_type=> $val){
                $result['other_more'][]=array(
                        'type'=>$leave_type[$l_type],
                        'leave_time'=>$val['all']
                        );
            }
            unset($result['tmp_other_more']);
        }
        //公出时间,1号-31的,不算钱
        $gcdata = $this->get_report_gongchu($uid,$start,$end);
        $result['oa_gc'] = $gcdata['oa_gc'];
        $result['oa_gc_passed'] = $gcdata['oa_gc_passed'];
        /*****************基本报表结束****计算上月未清开始****************/
        //开始计算上月未清取结算日之后天数开始,0901-0930这里取两个月user_last_leave_record
        $prev_start = date('Ymd',mktime(0,0,0,$month-1,1,$year));
        $prev_end = date('Ymd',mktime(0,0,0,$month,0,$year));
        $prev_data = $this->get_last_settlement_data($uid,$prev_start,$prev_end);

        $debug_info['prev_date'] = $prev_date;
        $debug_info['prev_data'] = $prev_data;
        $rep_bll = new Bll_Attendance_DailyReport();
        $prev_day_list = array();
        if(!empty($prev_data)){#没有请假通过的记录,如果那三天状态有异常就肯定是缺勤了
            foreach($prev_data as $val){
                $today = $val['dateline'];
                if(!in_array($today,$work_list)){//不是工作日
                    continue;
                }
                if($today <=$end_date){//小于入职时间的不算
                    continue;
                }
                if($dimission_date && $today >$dimission_date){//大于离职时间的不算
                    continue;
                }
                if($is_sale_partment){
                    if($val['leave_type']==Const_LeaveType::LEAVE_TYPE_QUEQIN){
                        continue;
                    }
                }

                //如果打卡正常
                $dk_status=$rep_bll->get_one_accessday($uid,$today);
                if($dk_status['status'][0]==5 && $dk_status['status'][1]==6){
                    continue;
                }
                if ($userinfo['user_type'] == 1 && $today >= $userinfo['user_type_date']) {
                    if($dk_status['status'][0]==3 && $dk_status['status'][1]==4){
                        if(!empty($dk_status[0]['start_work'])){
                            continue;
                        }
                    }else{
                        $prev_day_list[]=$today;
                        continue;
                    }
                }
                $prev_day_list[]=$today;
                $acr=1;
                if($val['leave_apm']!=3){
                    $acr=0.5;
                }

                if($today <=$prev_date){//月耒请的假 0328
                    if($val['leave_type']==Const_LeaveType::LEAVE_TYPE_SHIJIA){//1-28号不计事假
                        continue;
                    }elseif ($val['leave_type']==Const_LeaveType::LEAVE_TYPE_BINGJIA && $prev_date !=date('Ymd',$curr_month_end)){
                        $result['oa_prexj'][$leave_type[$val['leave_type']]] -=$acr;
                        $oa_prexj_info[$today][$val['leave_type']] -=$acr;
                    }else{
                        $result['oa_prexj'][$leave_type[$val['leave_type']]] +=$acr;
                        $oa_prexj_info[$today][$val['leave_type']] +=$acr;
                    }
                }elseif($today>$prev_date && $today<$start){//小于下月1号的,如果结算为月底最后一天将不再走这个判断
                    //这时期不计年假
                    if($val['leave_type']==Const_LeaveType::LEAVE_TYPE_SHIJIA || $val['leave_type']==Const_LeaveType::LEAVE_TYPE_BINGJIA || $val['leave_type']==Const_LeaveType::LEAVE_TYPE_CHANQIANJIA ){
                        //if($val['leave_apm']==3){
                            $result['oa_prexj'][$leave_type[$val['leave_type']]] -=$acr;
                            $oa_prexj_info[$today][$val['leave_type']] -=$acr;
                        //}else{//TODO是不是不需要这一步的处理
                        //    $result['oa_prexj'][$leave_type[$val['leave_type']]] +=$acr;
                        //    $oa_prexj_info[$today][$val['leave_type']] +=$acr;
                        //}
                    }
                }
            }
        }
        //print_r($result);
        //查看最后天不在请假，而状态还异常的,如果是上月未扣的数据将不正处理
        //0729-0801
        $last_where=array(#查询上个月结算日到这个月1日的假
                'user_id'=>$uid,
                "dateline >$prev_date AND dateline <$start AND 1=?"=>1
        );
        $last_list = $this->get_kq_dao()->find($last_where);

        if(!empty($last_list)){
            foreach ($last_list as $val){
                $today = $val['dateline'];
                if(!in_array($today,$work_list)){//不是工作日
                    continue;
                }
                if($today <=$end_date){//小于入职时间的不算
                    continue;
                }
                if($dimission_date && $today >$dimission_date){//大于离职时间的不算
                    continue;
                }
                if($today <20120701){
                    continue;
                }
                if($is_sale_partment){
                    continue;
                }
                if(in_array($today,$prev_day_list)){//上月未扣里的,说明是请过的假的
                    continue;
                }
                if ($userinfo['user_type'] == 1 && $today >= $userinfo['user_type_date']) {
                    if($val['am_status']==3 && $val['pm_status']==4){
                        if(!empty($access_record[$today]['start_work'])){
                            continue;
                        }
                    }else{
                        continue;
                    }
                }
                if($val['am_status']==3){
                    $result['oa_prexj'][$leave_type[14]] -=0.5;
                    $oa_prexj_info[$today][14] -=0.5;
                }
                if($val['pm_status']==4){
                    $result['oa_prexj'][$leave_type[14]] -=0.5;
                    $oa_prexj_info[$today][14] -=0.5;
                }
            }
        }

        //如果员工是上月结算日后入职的需要记入上月未扣 28-0801,20121-11采用自然月结算，将不再会有这个计算
        if($end_date > $prev_date  && substr($prev_date,4,2)==substr($end_date,4,2)){
            //如果是当月最后一天入职的,上周四就已添加员工
            if(!empty($last_list)){
                $v_key =$end_date.'入职';
                foreach($last_list as $val){
                    $today = $val['dateline'];
                    if(!in_array($today,$work_list)){//不是工作日
                        continue;
                    }
                    if($today <$end_date){//小于入职时间的不算
                        continue;
                    }
                    if($dimission_date && $today >$dimission_date){//大于离职时间的不算
                        continue;
                    }
                    if(in_array($today,$prev_day_list)){//上月未扣里的,说明是请过的假的
                        continue;
                    }
                    if($today==$end_date){
                        $result['oa_prexj'][$v_key] +=1;
                    }else{
                        if($val['am_status']==5 && empty($val['am_type'])){
                            $result['oa_prexj'][$v_key] +=0.5;
                        }
                        if($val['pm_status']==6 && empty($val['pm_type'])){
                            $result['oa_prexj'][$v_key] +=0.5;
                        }
                    }
                }
                if(!empty($result['oa_prexj'][$v_key])){
                    //$result['oa_prexj_info'][$today.'-999'] = $result['oa_prexj'][$v_key];
                    $oa_prexj_info[$today][999] = $result['oa_prexj'][$v_key];
                }
            }
        }
        if(isset($result['oa_prexj'][$leave_type[14]]) && $result['oa_prexj'][$leave_type[14]]==0){
            unset($result['oa_prexj'][$leave_type[14]]);
        }
        //$result['oa_prexj_info']['20120928-7']=0.5;
        //$result['oa_prexj_info']['20120929-14']=-0.5;
        if(!empty($oa_prexj_info)){
            foreach($oa_prexj_info as $key=>$val){
                foreach($val as $l_type=>$value){
                    if($l_type==999){
                        $result['oa_prexj_info'][$l_type] = $end_date.'入职'.$value;
                    }else{
                        $result['oa_prexj_info'][$key.'-'.$l_type]=date('m-d',strtotime($key)).$leave_type[$l_type].$value;
                    }
                }
            }
            $result['oa_prexj_info_debug'] = $oa_prexj_info;// for phpunit
        }
        $debug_info['have_half_day'] = $have_half_day;
        $debug_info['userinfo']=$userinfo;
        $result['debug']=$debug_info;
        //echo "<pre>";
        //print_r($result);
        //echo "</pre>";
        return $result;
    }

    /**
     * 得到公出的审批和未审批  1号-30的
     */
    public function get_report_gongchu($uid,$start,$end){
        $result = array(
                'oa_gc'=>0,
                'oa_gc_passed'=>0,
                );
        $where = array(//这里先不管用状态
                'user_id'=>$uid,
                "dateline >=$start AND dateline <=$end AND 1=?"=>1
        );
        $data = $this->get_curr_dao()->find($where);
        if(empty($data)){
            return $result;
        }
        foreach($data as $val){
            if($val['leave_type']==3 ){
                if($val['leave_status']==1 || $val['leave_status']==2){
                    $result['oa_gc'] += $val['leave_time'];
                    if($val['leave_status']==2){
                        $result['oa_gc_passed'] += $val['leave_time'];
                    }
                }
            }
        }
        return $result;
    }
    /**
     * 取当月结算日之后到月底这几天是否有提前请假的，
     * //0828-0901
     * @param int $uid
     * @param int $start
     * @param int $end
     */
    public function get_ext_record($uid,$start,$end){
        if($this->report_end==$start){//如果是结算日等于月最后一天.就不用查询
            return array();
        }
        $ext_where = array(//这里先不管用状态
                'user_id'=>$uid,
                "dateline >$start AND dateline <$end AND 1=?"=>1
        );
        $record_ext = $this->get_next_dao()->find($ext_where);
        $day_list = array();
        //主要针对在结算日之前就请了结算日之后到月未的假
        if(!empty($record_ext)){//已经请过的假了,合并到day_list里
            $i=100;
            foreach($record_ext as $val){
                $day_list[$i]=array(
                        'id' => $i,
                        'user_id' => $uid,
                        'dateline' => $val['dateline'],
                        'am_status' => 5,
                        'pm_status' => 6,
                        'is_later' => 0,
                        'leave_early' => 0,
                        'is_curr'=>1,//这是为了标记提前请了结算日之后的假
                );
                $day_list[$i]['days']=0;
                if($val['am_leave_status']==1||$val['am_leave_status']==2){
                    $day_list[$i]['days']+=0.5;
                    $day_list[$i]['am_type']=$val['am_type'];
                    $day_list[$i]['am_leave_status']=$val['am_leave_status'];
                }
                if($val['pm_leave_status']==1||$val['pm_leave_status']==2){
                    $day_list[$i]['days']+=0.5;
                    $day_list[$i]['pm_type']=$val['pm_type'];
                    $day_list[$i]['pm_leave_status']=$val['pm_leave_status'];
                }
                $i++;
            }
        }
        //出差
        $record_cc = $this->get_curr_dao()->find($ext_where);
        if(!empty($record_cc)){//已经请过的假了,合并到day_list里
            $j=200;
            foreach($record_cc as $val){
                $day_list[$j]=array(
                        'id' => $j,
                        'user_id' => $uid,
                        'dateline' => $val['dateline'],
                        'am_status' => 5,
                        'pm_status' => 6,
                        'is_later' => 0,
                        'leave_early' => 0,
                        'is_curr'=>1,//这是为了标记提前请了结算日之后的假
                );
                $day_list[$j]['days']=0;
                if($val['leave_apm']==3){
                    $day_list[$j]['days'] =1;
                    $day_list[$j]['am_type']=$val['leave_type'];
                    $day_list[$j]['am_leave_status']=$val['leave_status'];
                    $day_list[$j]['pm_leave_status']=$val['leave_status'];
                    $day_list[$j]['pm_type']=$val['leave_type'];
                }elseif($val['leave_apm']==1){
                    $day_list[$j]['days']+=0.5;
                    $day_list[$j]['am_type']=$val['leave_type'];
                    $day_list[$j]['am_leave_status']=$val['leave_status'];
                }elseif($val['leave_apm']==2){
                    $day_list[$j]['days']+=0.5;
                    $day_list[$j]['pm_type']=$val['leave_type'];
                    $day_list[$j]['pm_leave_status']=$val['leave_status'];
                }
                $j++;
            }
        }
        return $day_list;
    }
    /**
     * 如面有公用的方法，这里暂时使用
     * 当月入职与当月离职
     * @param unknown_type $userinfo
     * @param unknown_type $start
     * @param unknown_type $end
     * @return number
     */
    public function get_curr_month_n_work($userinfo,$start,$end){
        $unix_start = strtotime($start);
        $unix_dimiss = strtotime($userinfo['dimission_date']);
        $dimission_date = intval(str_replace('-','',substr($userinfo['dimission_date'],0,10)));//入职时间
        $curr_not_work = 0;
        if ($dimission_date && date('Ym',$unix_start) == date('Ym',$unix_dimiss)) {
            $curr_not_work += Tools_Tools::get_instance()->get_many_day(date('Y-m-d',$unix_dimiss), date('Y-m-d',strtotime($end)));
        }
        //当月入职
        if (date('Ym',$unix_start) == date('Ym',strtotime($userinfo['enter_date']))) {
            $curr_not_work += Tools_Tools::get_instance()->get_many_day(date('Y-m-d',$unix_start),$userinfo['enter_date']);
        }
        return $curr_not_work;
    }
    /**
     * 餐补计算
     * @param unknown_type $att_day 应出勤天数
     * @param unknown_type $act_day 实出勤天数 餐补计算
     */
    public function get_meal($att_day,$act_day) {
        $meal = APF::get_instance()->get_config('oa_meal');
        $meal = round($meal/$att_day*$act_day);
        return $meal;
    }
    public function find_user_leave_daily_by_dateline($uid,$dateline){
        return $this->get_curr_dao()->find(array('user_id'=>$uid,'dateline'=>$dateline));
    }
    function find_user_leave_ext_by_dateline($uid,$dateline){
        return $this->get_next_dao()->find(array('user_id'=>$uid,'dateline'=>$dateline));
    }
    private function save_log($str){
        $strtxt=date('Y-m-d H:i:s')."==".$str;
        file_put_contents("/tmp/sql_".date('Y-m-d')."_leave.txt",$strtxt."\n",FILE_APPEND);
    }
    public function update_kq_status($data,$where){
        $this->save_log("UPDATE=user_day_status=".json_encode($data)."=====".json_encode($where));
        return $this->get_kq_dao()->update($data,$where);
    }

    public function update_record_prev($data,$where){
        $this->save_log("UPDATE=UserLastLeave=".json_encode($data)."=====".json_encode($where));
        return $this->get_prev_dao()->update($data,$where);
    }
    public function update_record_curr($data,$where){
        $this->save_log("UPDATE=user_leave_daily=".json_encode($data)."=====".json_encode($where));
        return $this->get_curr_dao()->update($data,$where);
    }
    public function update_record_next($data,$where){
        $this->save_log("UPDATE=UserLeaveRecordExt=".json_encode($data)."=====".json_encode($where));
        return $this->get_next_dao()->update($data,$where);
    }
    public function insert_record_prev($data){
        $this->save_log("INSERT=UserLastLeave=".json_encode($data));
        return $this->get_prev_dao()->insert($data);
    }

    public function insert_record_curr($data){
        $this->save_log("INSERT=user_leave_daily=".json_encode($data));
        return $this->get_curr_dao()->insert($data);
    }

    public function insert_record_next($data){
        $this->save_log("INSERT=UserLeaveRecordExt=".json_encode($data));
        return $this->get_next_dao()->insert($data);
    }
    /**
     * 请今天之后的假，那天默认状态肯定是缺勤
     * @param unknown_type $uid
     * @param unknown_type $dateline
     */
    public function insert_record_kq_status($uid,$dateline){
        $data=array(
                'user_id'=>$uid,
                'dateline'=>$dateline,
                'am_status'=>5,
                'pm_status'=>6,
                );
        return $this->get_kq_dao()->insert($data);
    }
    /**
     * 检测当天的user_day_status,有可能job还没有写入user_day_status表
     */
    private function _check_curr_day_record($uid,$day){
        $list = $this->get_kq_dao()->find(array('user_id'=>$uid,'dateline'=>$day));
        if(empty($list)){
            $this->insert_record_kq_status($uid,$day);
        }
    }
    public function insert_record_kq_status_multi($daylist,$uid){
        $today = date('Ymd');
        $this->_check_curr_day_record($uid,$today);
        $in=array();
        $i=0;
        $max=count($daylist);
        foreach($daylist as $day=>$val){
            if($day>$today){#如果是今天之后的数据需要写入user_day_status
                $in[]=array(
                'user_id'=>$uid,
                'dateline'=>$day,
                'am_status'=>5,
                'pm_status'=>6,
                );
                $i++;
            }
            if(count($in)==10 || $i==$max){
                $this->get_kq_dao()->batch_insert($in);
                $in=array();
            }

        }
        return true;
    }

    private function get_next_dao(){
        return $this->get_dao('Dao_Attendance_UserLeaveRecordExt');
    }
    private function get_prev_dao(){
        return $this->get_dao('Dao_Attendance_UserLastLeave');
    }
    private function get_curr_dao(){
        return $this->get_dao('Dao_Attendance_UserLeaveDaily');
    }
    public function get_kq_dao(){
        return $this->get_dao('Dao_Attendance_UserKqStatus');
    }
    /**
     * 所有上月未清数据记录的id
     */
    private $_prev_data;
    public function set_prev_data($uid,$start,$end,$test_data){
        $where=array(
                'user_id'=>$uid,
                "dateline >=$start AND dateline <=$end AND 1=?"=>1
        );
        $key = join('_',$where);
        $this->_prev_data[$key] = $test_data;
    }
    public function get_prev_data($where){
        $key = join('_',$where);
        if(!($this->_prev_data && isset($this->_prev_data[$key]))){
            $this->_prev_data[$key] = $this->get_prev_dao()->find($where);
        }
        return $this->_prev_data[$key];
    }
    private $_curr_data;
    public function set_curr_data($uid,$start,$end,$test_data){
        $where=array(
                'user_id'=>$uid,
                "dateline >=$start AND dateline <=$end AND 1=?"=>1
        );
        $key = join('_',$where);
        $this->_curr_data[$key] = $test_data;
    }
    public function get_curr_data($where){
        $key = join('_',$where);
        if(!($this->_curr_data && isset($this->_curr_data[$key]))){
            $this->_curr_data[$key] = $this->get_curr_dao()->find($where);
        }
        return $this->_curr_data[$key];
    }
    private $_next_data;
    public function set_next_data($uid,$start,$end,$test_data){
        $where=array(
                'user_id'=>$uid,
                "dateline >=$start AND dateline <=$end AND 1=?"=>1
        );
        $key = join('_',$where);
        $this->_next_data[$key] = $test_data;
    }
    public function get_next_data($where){
        $key = join('_',$where);
        if(!($this->_next_data && isset($this->_next_data[$key]))){
            $this->_next_data[$key] = $this->get_next_dao()->find($where);
        }
        return $this->_next_data[$key];
    }
    private $_special_leave_time ;
    public function set_special_leave_time($special_leave_time){
        $this->_special_leave_time = $special_leave_time;
    }
    public function get_special_leave_time(){
        if(!$this->_special_leave_time){
            $this->_special_leave_time = Tools_Tools::get_instance()->special_leave_time();
        }
        return $this->_special_leave_time;
    }
    private function _other_special_days(){
        return array(
            '2013-02-01'=>array('start_time'=>'9:10','leave_time'=>'10:00')
        );
    }
    /**
     * 数据处理成页面显示所需
     */
    private function _do_to_view(&$result,&$leave_data,$end_date,$dimission_date,$userinfo){
        //特殊下班上班时间
        $special_leave_time = $this->get_special_leave_time();
        if($userinfo['city_name']=='上海'){
            $other_day=$this->_other_special_days();
            foreach($other_day as $k=>$val){
                $special_leave_time[$k]=$val;
            }
        }

        $now_date = intval(date('Ymd'));
        $now_time = intval(date('Hi'));
        foreach($result as $index => $value){
            //时间
            $result[$index]['view_date'] = $value['month'].'月'.$value['day'].'日&nbsp;&nbsp;周'.$value['week'];//日期
            $result[$index]['view_work'] = '';//上班时间
            $result[$index]['view_record'] = '';//考勤状态
            $result[$index]['view_detail'] = '';//说明
            if($value['dateline'] < $end_date){
                $result[$index]['view_record'] = '无考勤数据';
                continue;
            }elseif($dimission_date && $value['dateline'] > $dimission_date){
                $result[$index]['view_record'] = '无考勤数据';
                continue;
            }elseif($value['dateline'] > $now_date){
                $result[$index]['view_record'] = '无考勤数据';
                continue;
            }elseif($value['dateline'] < $now_date){
                $this->_do_work_time($result,$index,$value,false,$special_leave_time);
                $this->_do_error_record($result,$index,$value,$leave_data,$special_leave_time,false);
            }elseif($value['dateline'] == $now_date){
                $this->_do_work_time($result,$index,$value,true,$special_leave_time);
                $this->_do_error_record($result,$index,$value,$leave_data,$special_leave_time,true);
            }
        }
        //假期抵消异常状态
        $this->_do_leave_apply_to_remove_error_status($result,$leave_data,$special_leave_time);
        //上午缺勤，下午缺勤处理
        $this->_do_leave_no_record($result,$leave_data);
        //销售和非上海人员
        $this->_do_work_noneed_record($result,$leave_data,$userinfo);
        //节假日
        $this->_do_work_noneed_time($result);
        //离职入职
        $this->_do_enter_dimission_date($result);
        $res = array();
        foreach($result as $index => $value){
            $res[$index]['view_date']   = $value['view_date'];
            $res[$index]['view_work']   = $value['view_work'];
            $res[$index]['view_record'] = $value['view_record'];
            $res[$index]['view_detail'] = $value['view_detail'];
            $res[$index]['week']        = $value['week'];
            $res[$index]['worktime']    = $value['worktime']?$value['worktime']:'';
            $res[$index]['workendtime'] = $value['workendtime']?$value['workendtime']:'';
            $res[$index]['kq_detail'] = $value['view_work'] == '正常'?'正常':'';
            if(isset($value['kq_detail']) && isset($value['kq_detail']['start_work']) && !$this->is_self()){
                $res[$index]['kq_detail'] = substr($value['kq_detail']['start_work'], 0,2).':'.substr($value['kq_detail']['start_work'], 2).'-';
                $res[$index]['kq_detail'] .= substr($value['kq_detail']['end_work'], 0,2).':'.substr($value['kq_detail']['end_work'], 2);
            }
        }
        unset($result);
        //逆序
        krsort($res);
        return $res;
    }
    private function _do_enter_dimission_date(&$result){

        foreach($result as $index => $value){
            $now = intval($index);
            $userinfo = $this->get_user_info($value['user_id']);

            $enter_date = intval(str_replace('-','',substr($userinfo['enter_date'],0,10)));//入职时间
            $dimission_date = intval(str_replace('-','',substr($userinfo['dimission_date'],0,10)));//入职时间
            if($now < $enter_date){
                $result[$index]['view_date']   = $value['view_date'];
                $result[$index]['view_work']   = '正常';
                $result[$index]['view_detail'] = '';
                $result[$index]['week']        = $value['week'];
                $result[$index]['worktime']    = '';
                $result[$index]['workendtime'] = '';
                $result[$index]['kq_detail'] = "";
                $result[$index]['view_record'] = "未入职";
            }elseif($now > $dimission_date && $dimission_date){
                $result[$index]['view_date']   = $value['view_date'];
                $result[$index]['view_work']   = '正常';
                $result[$index]['view_detail'] = '';
                $result[$index]['week']        = $value['week'];
                $result[$index]['worktime']    = '';
                $result[$index]['workendtime'] = '';
                $result[$index]['kq_detail'] = "";
                if($result[$index]['view_record']){
                    $result[$index]['view_record'] = "离职";
                }
            }
        }
    }
    /**
     * 假期抵消异常状态
     */
    private function _do_leave_apply_to_remove_error_status(&$result,$leave_data,$special_leave_time){
        $res = array('未审核','已批准');
        $err = array('迟到','早退','上午缺勤','下午缺勤','全天缺勤','缺勤');
        foreach($result as $day=>$value){
            //全天情况
            if(isset($value['apm'])){
               $this->_do_leave_apply_to_remove_error_status_on_leave($result,$day,$value,$leave_data,'apm',$err,$special_leave_time);
            }
            if(isset($value['am'])){
                $this->_do_leave_apply_to_remove_error_status_on_leave($result,$day,$value,$leave_data,'am',array('迟到','上午缺勤'),$special_leave_time);
            }
            if(isset($value['pm'])){
               $this->_do_leave_apply_to_remove_error_status_on_leave($result,$day,$value,$leave_data,'pm',array('早退','下午缺勤'),$special_leave_time);
            }
        }
    }
    /**
     * 非请假抵消未提交异常
     */
    private function _do_leave_apply_to_remove_error_status_on_leave(&$result,$day,$value,$leave_data,$type,$recode_type,$special_leave_time){
        $res = array('未审核','已批准');
        $temp_is_apm = false;
        foreach($value[$type] as $index_am=>$value_am){
            if(isset($value_am['leave_id']) && in_array($leave_data[$value_am['leave_id']]['status'],$res) && $value_am['leave_type']!=Const_LeaveType::LEAVE_TYPE_GONGCHU){
                $temp_is_apm = true;
            }elseif(isset($value_am['leave_id']) && in_array($leave_data[$value_am['leave_id']]['status'],$res) && $value_am['leave_type']==Const_LeaveType::LEAVE_TYPE_GONGCHU){
                $temp_is_apm = false;//公出特殊替换
                //公出抵消异常
                $is_am_pm_error = $this->_do_gongchu_error($leave_data[$value_am['leave_id']],$value['kq_detail'],$special_leave_time);
                if($is_am_pm_error){
                    foreach($value['view_record'] as $index_vrecord=>$value_vrecord){
                        if(!isset($value_vrecord['leave_id']) && in_array($value_vrecord['type'],$is_am_pm_error)){
                            unset($result[$day]['view_record'][$index_vrecord]);
                            unset($result[$day]['view_detail'][$index_vrecord]);
                        }
                    }
                }
            }
        }
        if($temp_is_apm){
            foreach($value['view_record'] as $index_vrecord=>$value_vrecord){
                if(!isset($value_vrecord['leave_id']) && in_array($value_vrecord['type'],$recode_type)){
                    unset($result[$day]['view_record'][$index_vrecord]);
                    unset($result[$day]['view_detail'][$index_vrecord]);
                }
            }
        }
    }
    private function _do_gongchu_error($gc_leave,$kq_detail,$special_leave_time){
        $start_leave = intval(date('Hi',strtotime($gc_leave['start_time'])));
        $end_leave = intval(date('Hi',strtotime($gc_leave['end_time'])));
        $start_work = 0;
        $end_work = 0;
        if(!empty($kq_detail)){
            $start_work = intval($kq_detail['start_work']);
            $end_work = intval($kq_detail['end_work']);
        }
        $index_2 = date('Y-m-d',strtotime($gc_leave['end_time']));
        $temp_start = 910;
        $temp_end   = 1800;
        if(isset($special_leave_time[$index_2])){
            $temp_start = intval(date('Hi',strtotime($special_leave_time[$index_2]['start_time'])));
            $temp_end = intval(date('Hi',strtotime($special_leave_time[$index_2]['leave_time'])));
        }
        //迟到
        if($temp_start == 910 && $start_leave < $temp_start && $start_work > 910 && $start_work <= 930){
            return array('迟到');
        }
        //早退
        elseif($temp_end == 1800 && $end_leave >= $temp_end && $end_work >= 1730 && $end_work < 1800){
            return  array('早退');
        }
        //全天缺勤
        elseif($start_leave <= $temp_start && $end_leave >= $temp_end){
            return  array("上午缺勤","下午缺勤");
        }
        //上午缺勤
        elseif((!$start_work && $start_leave <= $temp_start && $end_leave >=1200) || ($start_work && $start_leave <= $temp_start && $start_work <= $end_leave)){
            return  array("上午缺勤");
        }
        //下午缺勤
        elseif((!$end_work && $end_leave >= $temp_end && $start_leave <=1400) || ($end_work && $end_leave >= $temp_end && $end_work >= $start_leave)){
            return  array("下午缺勤");
        }
        return '';
    }
    /**
     * no use
     * 公出抵消异常
     */
    private function _do_leave_apply_to_remove_error_status_on_gongchu(&$result,$day,$leave_data){
        $rep_bll = new Bll_Attendance_DailyReport();
        $res = $rep_bll->travel_to_kq_status($leave_data['user_id'],$day,strtotime($leave_data['start_time']),strtotime($leave_data['end_time']));
        //上午正常，可以覆盖
        if($res[0] == Const_LeaveType::KQ_AM_STATUS_5){
            $this->_do_leave_apply_to_remove_error_status_on_am($result,$day,$leave_data['id']);
        }
        //下午正常，可以
        if($res[1] == Const_LeaveType::KQ_PM_STATUS_6){
            $this->_do_leave_apply_to_remove_error_status_on_pm($result,$day,$leave_data['id']);
        }
    }
    /**
     * 上午缺勤，下午缺勤处理
     */
    private function _do_leave_no_record(&$result,$leave_data){
        $err = array('迟到','早退','上午缺勤','下午缺勤','全天缺勤');
        foreach($result as $day=>$value){
            if(empty($value['view_record']) || !is_array($value['view_record'])){
                continue;
            }
            $res = array();
            foreach($value['view_record'] as $index_other=>$value_other){
                $res['type'][] = $value_other['type'];
                if(in_array($value_other['type'], $err)){
                   $result[$day]['view_record'][$index_other]['type'] = '<span class="chi">'.$value_other['type'].'</span>';
                }
                $res[$value_other['type']]['index'] = $index_other;
                $res[$value_other['type']]['id'] = isset($value_other['leave_id'])?$value_other['leave_id']:0;
            }
           if(!empty($res) && in_array('上午缺勤',$res['type']) && in_array('下午缺勤',$res['type']) && !$res['上午缺勤']['id'] && !$res['下午缺勤']['id']){
               $index_am = $res['上午缺勤']['index'];
               $index_pm = $res['下午缺勤']['index'];
               unset($result[$day]['view_record'][$index_pm]);
               unset($result[$day]['view_detail'][$index_pm]);
               $result[$day]['view_record'][$index_am]['type'] = '<span class="chi">全天缺勤</span>';
           }
        }
    }


    /**
     * 节假日
     * @param unknown_type $result
     */
    private function _do_work_noneed_time(&$result){
        $holiday = Tools_Tools::get_instance()->each_year_holiday_country();
        $holiday_country = Tools_Tools::get_instance()->holiday_country();
        $holiday = array_merge($holiday_country,$holiday);
        $special_work_day = Tools_Tools::get_instance()->special_work_day();

        foreach ($result as $day =>$val){
            if($val['week'] != '六' && $val['week'] != '日') {
                if(in_array($this->_format_date_normal($day),$holiday)) {
                    $result[$day]['view_work'] = '';//上班时间
                    if(!empty($val['kq_detail'])){
                        $result[$day]['view_work'] = substr($val['kq_detail']['start_work'],0,2).':'.substr($val['kq_detail']['start_work'],2).'-'.substr($val['kq_detail']['end_work'],0,2).':'.substr($val['kq_detail']['end_work'],2);
                    }

                    $result[$day]['view_record'] = '法定节假日';//考勤状态
                    $result[$day]['view_detail'] = '';//说明
                }
            }else{
                //用户自己查看
                if(!in_array($this->_format_date_normal($day),$special_work_day)){
                        $result[$day]['view_detail'] = '';//说明
                        if(isset($_SESSION['user_id']) && $val['user_id'] == $_SESSION['user_id']){
                             $result[$day]['view_record'] = '';//考勤状态
                             $result[$day]['view_work'] = '';//上班时间
                        }else{
                            if(!empty($val['kq_detail'])){
                                $result[$day]['view_record'] = '周末加班辛苦了';//考勤状态
                            }else{
                                $result[$day]['view_record'] = '';//考勤状态
                                $result[$day]['view_work'] = '';//上班时间
                            }
                         }
                     }
                }
        }
    }
    /**
     * 销售和非上海人员和特殊班别
     * @param unknown_type $result
     */
    private function _do_work_noneed_record(&$result,$leaves,$userinfo){
        $err = array('公出','出差','事假','病假','年假','丧假','婚假','产检','产前假','产假','陪产假');
        //$users_id = $this->bll_user->get_sale_and_not_in_shanghai(); //old method
        $sale_department = APF::get_instance()->get_config('sale_department');
        $city_card = APF::get_instance()->get_config('city_card');
        $city_names = array_values($city_card);
        foreach ($result as $day =>$val){
            //销售和非开通打卡机的城市人员
            if(!in_array($userinfo['city_name'],$city_names) || !empty($sale_department[$userinfo['department_id']])){
                    if(isset($val['am']) || isset($val['pm']) || isset($val['apm'])){
                        if(!empty($val['view_record']) && is_array($val['view_record'])){
                            foreach($val['view_record'] as $index_vrecord=>$value_vrecord){
                                if(!in_array($value_vrecord['type'], $err)){
                                    unset($result[$day]['view_record'][$index_vrecord]);
                                    unset($result[$day]['view_detail'][$index_vrecord]);
                                }
                            }
                        }
                    }
                    else{
                        $result[$day]['view_work'] = '正常';//上班时间
                        $result[$day]['view_detail'] = '';//说明
                        $result[$day]['view_record'] = '<span class="img1">&nbsp;</span>';//考勤状态
                    }
                }
                //特殊班别，至少有一次打卡记录,后一个条件为曾经是特殊班别
                if(($userinfo['user_type'] && $userinfo['user_type_date'] <= $day) || (!$userinfo['user_type'] && $userinfo['user_type_date']>0 && $day<=$userinfo['user_type_date'])){
                    //if($val['dateline'] == date('Ymd')){

                    //}else{
                        if(!empty($val['kq_detail']) && empty($leaves)){
                            $result[$day]['view_work'] = '正常';//上班时间
                            $result[$day]['view_detail'] = '';//说明
                            $result[$day]['view_record'] = '<span class="img1">&nbsp;</span>';//考勤状态
                        }elseif(empty($val['kq_detail']) && !empty($leaves)){
                            $result[$day]['view_work'] = '';//上班时间
                        }elseif(!empty($val['kq_detail']) && !empty($leaves)){
                            foreach($val['view_record'] as $in=>$v){
                                if(!isset($v['leave_id'])){
                                   if(!empty($result[$day]['view_detail'])){
                                        unset($result[$day]['view_detail'][$in] );
                                        unset($result[$day]['view_record'][$in] );
                                   }
                                }
                            }
                        }
                    //}
                }
        }
    }

    /**
     * 处理上班时间
     * @param unknown_type $result
     * @param unknown_type $index
     * @param unknown_type $value
     * @param unknown_type $now_time
     */
    private function _do_work_time(&$result,$index,$value,$is_now,$special_leave_time){
        $result[$index]['worktime'] = '';
        $result[$index]['workendtime'] = '';
        if(!empty($value['kq_detail'])){
            $temp = array();
            $keep_date = $value['kq_detail']['access_date'];
            $temp['end'] = ($value['kq_detail']['end_work'])?substr($value['kq_detail']['end_work'],0,2).":".substr($value['kq_detail']['end_work'],2,2):0;
            $result[$index]['worktime'] = $this->get_work_time($value['kq_detail']['start_work'],$value['kq_detail']['end_work']);
            $result[$index]['workendtime'] = $this->get_workend_time($keep_date,$temp['end']);
        }

        if(empty($value['work_time_txt'])) {
            $result[$index]['view_work'] = '';
            if($value['am_status'] == Const_LeaveType::KQ_AM_STATUS_5 && $value['pm_status'] == Const_LeaveType::KQ_PM_STATUS_6 && !isset($value['am']) && !isset($value['pm']) && !isset($value['apm'])){
                if(!empty($value['kq_detail']) || $value['dateline'] == date('Ymd') && date('Hi') <1100){
                    $result[$index]['view_work'] = '正常';
                }else{
                    $result[$index]['view_work'] = '';
                }
            }
        }elseif($value['work_time_txt'] == '正常' && !isset($value['am']) && !isset($value['pm']) && !isset($value['apm'])){
            $result[$index]['view_work'] = $value['work_time_txt'];
        }elseif(!empty($value['kq_detail'])){
            $class_str = "";//加红
            $class_str_end="";//加红
            $start_work = $value['kq_detail']['start_work'];
            $end_work = $value['kq_detail']['end_work'];

            $index_2 = date('Y-m-d',strtotime($index));
            $temp_start = 910;
            $temp_end   = 1800;
            if(isset($special_leave_time[$index_2])){
                $temp_start = intval(date('Hi',strtotime($special_leave_time[$index_2]['start_time'])));
                $temp_end = intval(date('Hi',strtotime($special_leave_time[$index_2]['leave_time'])));
            }
            if(intval($start_work) > $temp_start){
                $class_str = 'class="chi"';
            }
            if($is_now){
                $result[$index]['view_work'] = '<span '.$class_str.'>'.substr($start_work,0,2).':'.substr($start_work,2).'</span>';
            }else{
                if(intval($end_work) < $temp_end){
                    $class_str_end = 'class="chi"';
                }
                $result[$index]['view_work'] = '<span '.$class_str.'>'.substr($start_work,0,2).':'.substr($start_work,2).'</span>-<span '.$class_str_end.'>'.substr($end_work,0,2).':'.substr($end_work,2).'</span>';
            }
        }
    }
    /**
     * 处理考勤状态和说明
     * @param unknown_type $result
     * @param unknown_type $index
     * @param unknown_type $value
     * @param unknown_type $now_time
     */
    private function _do_error_record(&$result,$index,$value,$leaves,$special_leave_time,$is_now){
        apf_require_class('Const_LeaveType');
        if($value['work_time_txt'] == '正常' && !isset($value['am']) && !isset($value['pm']) && !isset($value['apm'])){
            $result[$index]['view_record'] = '<span class="img1">&nbsp;</span>';
        }elseif($value['am_status'] == Const_LeaveType::KQ_AM_STATUS_5 && $value['pm_status'] == Const_LeaveType::KQ_PM_STATUS_6 && !isset($value['am']) && !isset($value['pm']) && !isset($value['apm'])){
            if(empty($value['kq_detail']) && $value['dateline'] == date('Ymd') && date('Hi') <1100){//9:40之前情况
                $result[$index]['view_record'] = '<span class="img1">&nbsp;</span>';
            }else{
                $index_2 = date('Y-m-d',strtotime($index));
                $temp_start = 910;
                $temp_end   = 1800;
                if(isset($special_leave_time[$index_2])){
                    $temp_start = intval(date('Hi',strtotime($special_leave_time[$index_2]['start_time'])));
                    $temp_end = intval(date('Hi',strtotime($special_leave_time[$index_2]['leave_time'])));
                }
                $start_work = $value['kq_detail']['start_work'];
                $end_work = $value['kq_detail']['end_work'];
                if($start_work <= $temp_start && $end_work >= $temp_end){//job正常调整
                    $result[$index]['view_record'] = '<span class="img1">&nbsp;</span>';
                }else{//job未调整
                    $this->_do_job_no_do_right($result,$index,$value,$start_work,$temp_start,$end_work,$temp_end,$is_now);
                }
            }
        }
        else{
            //上午异常（迟到，缺勤），未申请，未批准
            $index_view_record = 0;
            if($value['am_status'] != Const_LeaveType::KQ_AM_STATUS_5 ){
                $this->_do_error_record_detail($result,$index,$value,$leaves,'am',$index_view_record);
            }
            //下午异常（早退，缺勤），未申请，未批准
            if($value['pm_status'] != Const_LeaveType::KQ_PM_STATUS_6 && !$is_now){
                $this->_do_error_record_detail($result,$index,$value,$leaves,'pm',$index_view_record);
            }
            //其它异常
            $this->_do_error_other_record($result,$index,$value,$leaves,$index_view_record);
        }
    }
    /**
     * job未调整
     */
    private function _do_job_no_do_right(&$result,$index,$value,$start_work,$temp_start,$end_work,$temp_end,$is_now){
        $view_record = array();
        $view_detail = array();
        $view_record['date'] = $this->_format_date_normal($value['dateline']);
        $status = 0;
        //全天缺勤
        if(($start_work > 930 && $start_work > $temp_start && $end_work < $temp_end && $end_work < 1730 && !$is_now) || (!$is_now && !$start_work && !$end_work)){
            $view_record['type'] = "全天缺勤";
            $status = 3;
            if($this->is_self()){
                $view_record['html_url'] .= '<a href="/delay/?type='.$status.'&amp;date='.$this->_format_date_normal($value['dateline']).'">[提交原因]</a>';
            }
            $result[$index]['view_record'][0] = $view_record;
            $result[$index]['view_detail'][0] = $view_detail;
        }else{
            //上午情况
            if($start_work > $temp_start && $start_work <= 930){//迟到
                $status = Const_LeaveType::LEAVE_TYPE_CHIDAO;
                $view_record['type'] = Const_LeaveType::get_kq_name($status);
            }elseif(($start_work > 930 && $start_work > $temp_start) || !$start_work){//上午缺勤
                $status = 3;
                $view_record['type'] = "上午缺勤";
            }
            if($this->is_self() && $status ){
                $view_record['html_url'] .= '<a href="/delay/?type='.$status.'&amp;date='.$this->_format_date_normal($value['dateline']).'">[提交原因]</a>';
            }
            if($status){
                $result[$index]['view_record'][0] = $view_record;
                $result[$index]['view_detail'][0] = $view_detail;
            }
            if(!$is_now){
                //下午情况
                $status = 0;
                if($end_work >= 1730 && $end_work < $temp_end){//早退
                    $status = Const_LeaveType::LEAVE_TYPE_ZAOTUI;
                    $view_record['type'] = Const_LeaveType::get_kq_name($status);
                }elseif($end_work < $temp_end && $end_work < 1730){//下午缺勤
                    $status = 3;
                    $view_record['type'] = "下午缺勤";
                }
                if($this->is_self() && $status){
                    $view_record['html_url'] .= '<a href="/delay/?type='.$status.'&amp;date='.$this->_format_date_normal($value['dateline']).'">[提交原因]</a>';
                }
                if($status){
                    $result[$index]['view_record'][1] = $view_record;
                    $result[$index]['view_detail'][1] = $view_detail;
                }
            }
        }
    }
    /**
     * 异常（迟到，缺勤），未申请，未批准
     * @param unknown_type $result
     * @param unknown_type $index
     * @param unknown_type $value
     * @param unknown_type $leaves
     * @param unknown_type $type
     */
    private function _do_error_record_detail(&$result,$index,$value,$leaves,$type,&$index_view_record){
        $view_record = array();
        $view_detail = array();
        $view_record['type'] = Const_LeaveType::get_kq_name($value[$type.'_status']);//打卡状态
        $leave = array();
        if(isset($value['apm'])){
            //$leave = $this->_is_have_leave($value['apm'],$value[$type.'_status']);
        }
        if(empty($leave) && isset($value[$type])){
            $leave = $this->_is_have_leave($value[$type],$value[$type.'_status']);
        }
        if(empty($leave)){
            $view_record['date'] = $this->_format_date_normal($value['dateline']);
            $status = $value[$type.'_status'];
            if($value[$type.'_status'] != Const_LeaveType::LEAVE_TYPE_CHIDAO && $value[$type.'_status'] != Const_LeaveType::LEAVE_TYPE_ZAOTUI){
                $status = 3;
            }
            if($this->is_self()){
                $view_record['html_url'] .= '<a href="/delay/?type='.$status.'&amp;date='.$this->_format_date_normal($value['dateline']).'">[提交原因]</a>';
            }
        }else{
            $view_record['leave_id'] = $leave['leave_id'];
            $view_record['leave_reason'] = $leaves[$leave['leave_id']]['leave_reason'];
            $view_record['leave_status'] = Const_LeaveType::get_leave_status_name($leave['leave_status']);

            $view_detail['leave_desc']= $leaves[$leave['leave_id']]['leave_desc'].'';//说明
            $view_detail['type'] = $leaves[$leave['leave_id']]['type'];
        }
        $result[$index]['view_record'][$index_view_record] = $view_record;
        $result[$index]['view_detail'][$index_view_record] = $view_detail;
        $index_view_record++;
    }
    /**
     * 其它异常情况处理
     * @param unknown_type $result
     * @param unknown_type $index
     * @param unknown_type $value
     * @param unknown_type $leaves
     */
    private function _do_error_other_record(&$result,$index,$value,$leaves,&$index_view_record){
        //上午情况
        if(isset($value['am'])){
            foreach($value['am'] as $one){
                if($one['leave_type'] != Const_LeaveType::kq_status_to_leave_status($value['am_status']) ){
                    $this-> _do_error_other_record_detail($result,$index,$value,$leaves,$one,'上午',$index_view_record);
                }
            }
        }
        //下午情况
        if(isset($value['pm'])){
            foreach($value['pm'] as $one){
                if($one['leave_type'] != Const_LeaveType::kq_status_to_leave_status($value['pm_status'])){
                    $this-> _do_error_other_record_detail($result,$index,$value,$leaves,$one,'下午',$index_view_record);
                }
            }
        }
        //全天情况
        if(isset($value['apm'])){
             foreach($value['apm'] as $one){
                $this-> _do_error_other_record_detail($result,$index,$value,$leaves,$one,'全天',$index_view_record);
            }
        }
    }
    /**
     * 其它异常详细处理
     * @param unknown_type $result
     * @param unknown_type $index
     * @param unknown_type $value
     * @param unknown_type $leaves
     * @param unknown_type $one
     * @param unknown_type $name
     */
    private function _do_error_other_record_detail(&$result,$index,$value,$leaves,$one,$name,&$index_view_record){
        $view_record = array();
        $view_detail = array();
        $view_record['leave_id'] = $one['leave_id'];
        $view_record['leave_reason'] = $leaves[$one['leave_id']]['leave_reason'];
        //$view_record['leave_status'] = Const_LeaveType::get_leave_status_name($one['leave_status']);
        $view_record['leave_status'] = $leaves[$one['leave_id']]['status'];

        $view_detail['leave_desc']= $leaves[$one['leave_id']]['leave_desc'].'';//说明
        $view_detail['type']= $leaves[$one['leave_id']]['type'].'';//类别
        //缺勤情况
        if($one['leave_type'] == Const_LeaveType::LEAVE_TYPE_QUEQIN){
            $view_record['type'] = $name.'缺勤';
        }else{
            $view_record['type'] = $leaves[$one['leave_id']]['type'];
            //病假，陪产假特殊处理
            if(($leaves[$one['leave_id']]['type'] == '病假' || $leaves[$one['leave_id']]['type'] == '陪产假') && empty($leaves[$one['leave_id']]['img'])){
                if((time() - $leaves[$one['leave_id']]['apply_time_ext']) < 604800) {
                    if($this->is_self()){
                     $view_record['upload_prove'] ="  <a href='/proof/?id=".$one['leave_id']."'>上传证明</a>";
                    }
                }
            }
            if(($leaves[$one['leave_id']]['type'] == '病假' || $leaves[$one['leave_id']]['type'] == '陪产假') && $leaves[$one['leave_id']]['img']) {
                $view_record['view_prove'] ="  <a href='/upload/attendance/".$leaves[$one['leave_id']]['img']."' target='_blank'>查看证明</a>";
                $view_record['view_prove']['img'] = $leaves[$one['leave_id']]['img'];
            }
        }
        $result[$index]['view_record'][$index_view_record] = $view_record;
        $result[$index]['view_detail'][$index_view_record] = $view_detail;
        $index_view_record++;
    }
    /**
     * 请假状态，找记录
     * @param unknown_type $leaves
     * @param unknown_type $type
     */
    private function _is_have_leave($leaves,$type){
        $result = array();
        if(empty($leaves)){
            return $result;
        }
        foreach($leaves as $one){
            if($one['leave_type'] == Const_LeaveType::kq_status_to_leave_status($type)){
                $result['leave_id'] = $one['leave_id'];
                $result['leave_status'] = $one['leave_status'];
            }
        }
        return $result;
    }
    /**
     * 时间处理  Ymd=>Y-m-d
     * @param unknown_type $date
     * @return string
     */
    private function _format_date_normal($date){
        return substr($date,0,4).'-'.substr($date,4,2).'-'.substr($date,6);
    }
    /**
     * 计算加班工时,默认从19:00后打卡，才算加班，加班时间从19:00到24:00
     * @param unknown_type $end
     */
    private function get_workend_time($day,$end = 0) {
        $d = 19;
        $result = '0';
        if(empty($end) || empty($day)) {
            return $result;
        }

        $nowday = $day.' '.$end;
        $time = strtotime($nowday);
        $h = date('H',$time);
        if($h>=$d) {
            $time = strtotime($nowday)-strtotime($day.' 18:00');
            $result = floor(($time/3600)*10)/10;
        }
        return $result;
    }
    /**
     * 计算工时
     */
    private function get_work_time($start = 0,$end = 0) {
        $result = '0';
        if(empty($start) || empty($end)) {
            return $result;
        }

        if ($start < 1200) {
            if ($end > 1300) {
                if ($end > 1800) {
                    $worktime = strtotime(1800)-strtotime($start) -3600;
                }else{
                    $worktime = strtotime($end)-strtotime($start) -3600;
                }
            }else{
                $worktime = strtotime($end)-strtotime($start);
            }

        }else
        {
            if ($end > 1800) {
                $worktime = strtotime(1800)-strtotime($start);
            }else
            {
                $worktime = strtotime($end)-strtotime($start);
            }
        }

        $worktime = floor(($worktime/3600)*10)/10;
        if($worktime<0){
            $worktime=0;
        }
        return $worktime;
    }
     /**
      * 查看员工剩余年假
      * @param array $uids
      * @return multitype:
      */
    public function get_surplus_annual_days($uids){
        $data = array();
        if(empty($uids)){
            return $data;
        }

        $user_bll = new Bll_Attendance_UserInfo();
        $user_data = $user_bll->get_user_by_ids($uids);

        $user_ext_bll = new Bll_Attendance_UserExt();
        $user_ext_data = $user_ext_bll->get_used_annual_by_ids($uids);

        $tools = Tools_Tools::get_instance();

        foreach($user_data as $val){
            $day = $tools->annual($val['enter_date']);
            if($day<=0){
                $data[$val['user_id']]=0;
            }else{
                $tm_day = 0;
                if(!empty($user_ext_data[$val['user_id']])){
                    $tm_day = $day - $user_ext_data[$val['user_id']]['annual_used'];
                }else{
                    $tm_day = $day;//还没有用过年假
                }
                $data[$val['user_id']] = $tm_day < 0 ? 0 : $tm_day;
            }
        }
        foreach($uids as $uid){
            if(empty($data[$uid])){
                $data[$uid] = 0;
            }
        }
        return $data;
    }


    /**
     * 取出某天公司所有人不再公司的小时数
     * @param unknown_type $date
     * @return multitype:|multitype:number unknown
     */
    public function get_leave_hours_by_date( $date ){
        if( empty($date) ){
            return array();
        }
        $prev_time=date('Ym',strtotime($date));
        $prev_work_day_list = Tools_Tools::get_instance()->actual_work_day_by_month_list($prev_time);//上个月需要上班的日子
        if(!in_array($date,$prev_work_day_list)){
            return array();
        }
        $date = mysql_escape_string($date);
        apf_require_class('Const_LeaveType');
        $exclude_type = array( Const_LeaveType::LEAVE_TYPE_QUEQIN, Const_LeaveType::LEAVE_TYPE_CHUCHA );
        $gc_hours = array();
        //从user_leave_record_ext获取请假时间
        $fields = array('user_id', 'am_type', 'am_leave_status', 'pm_type', 'pm_leave_status');
        $where = 'dateline='.$date;
        $leave_info = $this->get_next_dao()->find_short ($where, $order = null, $limit = 0, $offset = 0, $fields);
        //检查上午下午的请假类型以及是否被批准以便统计请假的小时数
        $leave_hours = array();
        foreach( $leave_info as &$v ){
            $am_hours = $pm_hours = $am_and_pm_hours = 0;
            //上午
            if( $v['am_leave_status'] == 2 && !in_array($v['am_type'], $exclude_type)){
                $am_hours = 4;
            }
            //下午
            if( $v['pm_leave_status'] == 2 && !in_array($v['pm_type'], $exclude_type)){
                $pm_hours = 4;
            }
            //上下午总时间
            $am_and_pm_hours = $am_hours + $pm_hours;
            if($am_and_pm_hours){
                //加上公出的时间
                if(empty($gc_hours[$v['user_id']])){
                    $gc_hours[$v['user_id']]  = $am_and_pm_hours;
                }else{
                    $gc_hours[$v['user_id']] += $am_and_pm_hours;
                }
            }
        }
        //出差
        $_where['dateline']= $date;
        $leave_daily = $this->get_curr_dao()->find($_where);
        if(!empty($leave_daily)){
            foreach( $leave_daily as $v ){
                if($v['leave_status']==2 && $v['leave_type']==Const_LeaveType::LEAVE_TYPE_CHUCHA){
                    $hours = $v['leave_time']==0.5 ? 4 : 8;
                    if(empty($gc_hours[$v['user_id']])){
                        $gc_hours[$v['user_id']]  = $hours;
                    }else{
                        $gc_hours[$v['user_id']] += $hours;
                    }
                }
            }
        }
        if(empty($gc_hours)){
            return array();
        }
        $user_dao = $this->get_dao('Dao_Attendance_UserInfo');
        $user_ids_str = join(',', array_keys($gc_hours));
        $where = 'user_id IN('.$user_ids_str.')';
        $fields = array('user_id,code');
        $codes = $user_dao->find_short($where, $order = null, $limit = 0, $offset = 0, $fields);
        $return = array();
        foreach( $codes as &$v ){
            $return[$v['code']] = $gc_hours[$v['user_id']];
        }
        return $return;
    }

}
